#ifndef __ResourceBackgroundQueue_H__
#define __ResourceBackgroundQueue_H__


#include "U2PreRequest.h"
#include "U2MemoryAllocatorConfig.h"
#include "U2SharedPtr.h"
#include "U2Singleton.h"
#include "U2Resource.h"
#include "U2WorkQueue.h"


U2EG_NAMESPACE_BEGIN


/// Identifier of a background process
typedef WorkQueue::RequestID BackgroundProcessTicket;

/** Encapsulates the result of a background queue request */
struct BackgroundProcessResult
{
	/// Whether an error occurred
	bool error;
	/// Any messages from the process
	U2String message;

	BackgroundProcessResult() : error(false) {}
};


/** This class is used to perform Resource operations in a
	background thread. 
@remarks
	All these requests are now queued via Root::getWorkQueue in order
	to share the thread pool amongst all background tasks. You should therefore
	refer to that class for configuring the behaviour of the threads
	themselves, this class merely provides an interface that is specific
	to resource loading around this common functionality.
@par
	The general approach here is that on requesting a background resource
	process, your request is placed on a queue ready for the background
	thread to be picked up, and you will get a 'ticket' back, identifying
	the request. Your call will then return and your thread can
	proceed, knowing that at some point in the background the operation will 
	be performed. In it's own thread, the resource operation will be 
	performed, and once finished the ticket will be marked as complete. 
	You can check the status of tickets by calling isProcessComplete() 
	from your queueing thread. 
*/
class _U2Share U2ResourceBackgroundQueue : public U2Singleton<U2ResourceBackgroundQueue>, public ResourceAlloc, 
	public WorkQueue::RequestHandler, public WorkQueue::ResponseHandler
{
public:
	/** This abstract listener interface lets you get notifications of
	completed background processes instead of having to poll ticket 
	statuses.
	@note
	For simplicity, these callbacks are not issued direct from the background
	loading thread, they are queued themselves to be sent from the main thread
	so that you don't have to be concerned about thread safety. 
	*/
	class _U2Share Listener
	{
	public:
		/** Called when a requested operation completes, queued into main thread. 
		@note
			For simplicity, this callback is not issued direct from the background
			loading thread, it is queued to be sent from the main thread
			so that you don't have to be concerned about thread safety. 
		*/
		virtual void operationCompleted(BackgroundProcessTicket ticket, const BackgroundProcessResult& result) = 0;
		/// Need virtual destructor in case subclasses use it
		virtual ~Listener() {}

	};

protected:

	u2uint16 mWorkQueueChannel;
	/** Enumerates the type of requests */
	enum RequestType
	{
		RT_INITIALISE_GROUP = 0,
		RT_INITIALISE_ALL_GROUPS = 1,
		RT_PREPARE_GROUP = 2,
		RT_PREPARE_RESOURCE = 3,
		RT_LOAD_GROUP = 4,
		RT_LOAD_RESOURCE = 5,
		RT_UNLOAD_GROUP = 6,
		RT_UNLOAD_RESOURCE = 7
	};
	/** Encapsulates a queued request for the background queue */
	struct ResourceRequest
	{
		RequestType type;
		U2String resourceName;
		U2ResourceHandle resourceHandle;
		U2String resourceType;
		U2String groupName;
		bool isManual; 
		U2ManualResourceLoader* loader;
		NameValuePairList* loadParams;
		Listener* listener;
		BackgroundProcessResult result;

		_U2Share friend std::ostream& operator<<(std::ostream& o, const ResourceRequest& r)
		{ (void)r; return o; }
	};

    typedef std::set<BackgroundProcessTicket> OutstandingRequestSet;	
	OutstandingRequestSet mOutstandingRequestSet;

	/// Struct that holds details of queued notifications
	struct ResourceResponse
	{
		ResourceResponse(U2ResourcePtr r, const ResourceRequest& req)
			: resource(r), request(req)
		{}

		U2ResourcePtr resource;
		ResourceRequest request;

		_U2Share friend std::ostream& operator<<(std::ostream& o, const ResourceResponse& r)
		{ (void)r; return o; }
	};

	BackgroundProcessTicket addRequest(ResourceRequest& req);

public:
	U2ResourceBackgroundQueue();
	virtual ~U2ResourceBackgroundQueue();

	/** Initialise the background queue system. 
	@note Called automatically by Root::initialise.
	*/
	virtual void initialise(void);

	/** Shut down the background queue system. 
	@note Called automatically by Root::shutdown.
	*/
	virtual void shutdown(void);

	/** Initialise a resource group in the background.
	@see ResourceGroupManager::initialiseResourceGroup
	@param name The name of the resource group to initialise
	@param listener Optional callback interface, take note of warnings in 
		the header and only use if you understand them.
	@returns Ticket identifying the request, use isProcessComplete() to 
		determine if completed if not using listener
	*/
	virtual BackgroundProcessTicket initialiseResourceGroup(
		const U2String& name, Listener* listener = 0);

	/** Initialise all resource groups which are yet to be initialised in 
		the background.
	@see ResourceGroupManager::intialiseResourceGroup
	@param listener Optional callback interface, take note of warnings in 
		the header and only use if you understand them.
	@returns Ticket identifying the request, use isProcessComplete() to 
		determine if completed if not using listener
	*/
	virtual BackgroundProcessTicket initialiseAllResourceGroups( 
		Listener* listener = 0);
	/** Prepares a resource group in the background.
	@see ResourceGroupManager::prepareResourceGroup
	@param name The name of the resource group to prepare
	@param listener Optional callback interface, take note of warnings in 
		the header and only use if you understand them.
	@returns Ticket identifying the request, use isProcessComplete() to 
		determine if completed if not using listener
	*/
	virtual BackgroundProcessTicket prepareResourceGroup(const U2String& name, 
		Listener* listener = 0);

	/** Loads a resource group in the background.
	@see ResourceGroupManager::loadResourceGroup
	@param name The name of the resource group to load
	@param listener Optional callback interface, take note of warnings in 
		the header and only use if you understand them.
	@returns Ticket identifying the request, use isProcessComplete() to 
		determine if completed if not using listener
	*/
	virtual BackgroundProcessTicket loadResourceGroup(const U2String& name, 
		Listener* listener = 0);


	/** Unload a single resource in the background. 
	@see ResourceManager::unload
	@param resType The type of the resource 
		(from ResourceManager::getResourceType())
	@param name The name of the Resource
	*/
	virtual BackgroundProcessTicket unload(
		const U2String& resType, const U2String& name, 
		Listener* listener = 0);

	/** Unload a single resource in the background. 
	@see ResourceManager::unload
	@param resType The type of the resource 
		(from ResourceManager::getResourceType())
	@param handle Handle to the resource 
	*/
	virtual BackgroundProcessTicket unload(
		const U2String& resType, U2ResourceHandle handle, 
		Listener* listener = 0);

	/** Unloads a resource group in the background.
	@see ResourceGroupManager::unloadResourceGroup
	@param name The name of the resource group to load
	@returns Ticket identifying the request, use isProcessComplete() to 
		determine if completed if not using listener
	*/
	virtual BackgroundProcessTicket unloadResourceGroup(const U2String& name, 
		Listener* listener = 0);


	/** Prepare a single resource in the background. 
	@see ResourceManager::prepare
	@param resType The type of the resource 
		(from ResourceManager::getResourceType())
	@param name The name of the Resource
	@param group The resource group to which this resource will belong
	@param isManual Is the resource to be manually loaded? If so, you should
		provide a value for the loader parameter
	@param loader The manual loader which is to perform the required actions
		when this resource is loaded; only applicable when you specify true
		for the previous parameter. NOTE: must be thread safe!!
    @param loadParams Optional pointer to a list of name/value pairs 
        containing loading parameters for this type of resource. Remember 
		that this must have a lifespan longer than the return of this call!
	*/
	virtual BackgroundProcessTicket prepare(
		const U2String& resType, const U2String& name, 
        const U2String& group, bool isManual = false, 
		U2ManualResourceLoader* loader = 0, 
		const NameValuePairList* loadParams = 0, 
		Listener* listener = 0);

	/** Load a single resource in the background. 
	@see ResourceManager::load
	@param resType The type of the resource 
		(from ResourceManager::getResourceType())
	@param name The name of the Resource
	@param group The resource group to which this resource will belong
	@param isManual Is the resource to be manually loaded? If so, you should
		provide a value for the loader parameter
	@param loader The manual loader which is to perform the required actions
		when this resource is loaded; only applicable when you specify true
		for the previous parameter. NOTE: must be thread safe!!
    @param loadParams Optional pointer to a list of name/value pairs 
        containing loading parameters for this type of resource. Remember 
		that this must have a lifespan longer than the return of this call!
	*/
	virtual BackgroundProcessTicket load(
		const U2String& resType, const U2String& name, 
        const U2String& group, bool isManual = false, 
		U2ManualResourceLoader* loader = 0, 
		const NameValuePairList* loadParams = 0, 
		Listener* listener = 0);
	/** Returns whether a previously queued process has completed or not. 
	@remarks
		This method of checking that a background process has completed is
		the 'polling' approach. Each queued method takes an optional listener
		parameter to allow you to register a callback instead, which is
		arguably more efficient.
	@param ticket The ticket which was returned when the process was queued
	@returns true if process has completed (or if the ticket is 
		unrecognised), false otherwise
	@note Tickets are not stored once complete so do not accumulate over 
		time.
	This is why a non-existent ticket will return 'true'.
	*/
	virtual bool isProcessComplete(BackgroundProcessTicket ticket);

	/** Aborts background process.
	*/
	void abortRequest( BackgroundProcessTicket ticket );

	/// Implementation for WorkQueue::RequestHandler
	bool canHandleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ);
	/// Implementation for WorkQueue::RequestHandler
	WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ);
	/// Implementation for WorkQueue::ResponseHandler
	bool canHandleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ);
	/// Implementation for WorkQueue::ResponseHandler
	void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ);

	/** Override standard U2Singleton retrieval.
    @remarks
    Why do we do this? Well, it's because the U2Singleton
    implementation is in a .h file, which means it gets compiled
    into anybody who includes it. This is needed for the
    U2Singleton template to work, but we actually only want it
    compiled into the implementation of the class based on the
    U2Singleton, not all of them. If we don't change this, we get
    link errors when trying to use the U2Singleton-based class from
    an outside dll.
    @par
    This method just delegates to the template version anyway,
    but the implementation stays in this single compilation unit,
    preventing link errors.
    */
    static U2ResourceBackgroundQueue& getSingleton(void);
    /** Override standard U2Singleton retrieval.
    @remarks
    Why do we do this? Well, it's because the U2Singleton
    implementation is in a .h file, which means it gets compiled
    into anybody who includes it. This is needed for the
    U2Singleton template to work, but we actually only want it
    compiled into the implementation of the class based on the
    U2Singleton, not all of them. If we don't change this, we get
    link errors when trying to use the U2Singleton-based class from
    an outside dll.
    @par
    This method just delegates to the template version anyway,
    but the implementation stays in this single compilation unit,
    preventing link errors.
    */
    static U2ResourceBackgroundQueue* getSingletonPtr(void);

};


U2EG_NAMESPACE_END


#endif

